package by.gamedev.site.client.app.ui;

import java.util.Collection;

import com.google.gwt.text.shared.AbstractRenderer;
import com.google.gwt.text.shared.Renderer;

/**
 * A renderer for Collections that is parameterized by another renderer.
 */
public class CollectionRenderer<E, R extends Renderer<E>, T extends Collection<E>> extends AbstractRenderer<T> {

    public static <E, R extends Renderer<E>, T extends Collection<E>> CollectionRenderer<E, R, T> of(final R r) {
        return new CollectionRenderer<E, R, T>(r);
    }

    private final R elementRenderer;

    public CollectionRenderer(final R elementRenderer) {
        this.elementRenderer = elementRenderer;
    }

    @Override
    public String render(final T t) {
        final StringBuffer toReturn = new StringBuffer();
        boolean first = true;
        if(t != null ) {
            for (final E e : t) {
                if(!first ) {
                    toReturn.append(',');
                } else {
                    first = false;
                }
                toReturn.append(elementRenderer.render(e));
            }
        }
        return toReturn.toString();
    }
}
